﻿using MKAdminCore.DTO.Web.Common;
using MKAdminCore.DTO.Web.File;
using MKAdminCore.ToolKit.Extensions;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace MKAdminCore.ToolKit.PosterImgHelper
{
    public class PosterImgHelper
    {
        /// <summary>
        /// 生成海报图
        /// </summary>
        /// <param name="title"></param>
        /// <param name="posterImg"></param>
        /// <returns></returns>
        public static async Task<HttpResponseResult<PosterCompoundModel>> CreatePosteImage(string title
            , string posterCoverUrl, double originalPrice, double finalPrice)
        {
            var result = new HttpResponseResult<PosterCompoundModel>() { Code = 400 };
            //海报尺寸
            int posterWidth = 750;
            Image imgSrc = new Bitmap(posterWidth, 1290);

            //海报左右边距
            int marginWidth = 30;
            //海报商品图上边距高度
            int productImgMarginTop = 30;
            //海报商品图下边距高度
            int productImgMarginBottom = 35;
            //海报商品图默认高度
            int productImgHeight = 690;

            //标题字体大小
            float titleSize = 28.0f;
            //标题每行高度
            int titleHeight = 42;
            //标题下边距高度
            int productTitleMarginBottom = 30;

            //二维码图片
            var rootPath = $@"{ Environment.CurrentDirectory}";
            var qrcodePath = $@"{rootPath}\wwwroot\images\50001.png";
            //淘宝logo图片
            string taobaoLogoImg = $@"{rootPath}\wwwroot\images\tblogo.png";
            //淘宝底部下边距
            int taobaoImgBottom = 30;

            int originalImgWidth = imgSrc.Width;
            int originalImgHeight = imgSrc.Height;

            using (Graphics g = Graphics.FromImage(imgSrc))
            {
                //背景色
                g.Clear(Color.White);

                //海报
                //using (Image imgPoster = Image.FromFile(posterImg))
                using (Image imgPoster = await UrlToImage(posterCoverUrl))
                {
                    //海报主图理想宽度
                    int posterCoverWidth = posterWidth;

                    int coverStartX = 0;
                    int coverStartY = 0;

                    g.DrawImage(imgPoster, new Rectangle(30, productImgMarginTop, productImgHeight, productImgHeight),
                            coverStartX, coverStartY, imgPoster.Width, imgPoster.Height, GraphicsUnit.Pixel);
                }

                //标题文字可输入区域宽度
                int textRangeWidth = imgSrc.Width - (marginWidth * 2) + 20;

                //商品标题
                using (Font fTitle = new Font("黑体", titleSize, FontStyle.Bold))
                {
                    using (Brush b = new SolidBrush(Color.FromArgb(43, 43, 43)))
                    {
                        var sizeT = g.MeasureString(title.Replace("\n", ""), fTitle);
                        //如果标题内容长度大于绘制区域宽度,则动态设置标题绘制区域高度
                        int rowCount = Convert.ToInt32(Math.Ceiling(sizeT.Width / textRangeWidth));
                        if (rowCount > 1)
                        {
                            titleHeight = 2 * titleHeight;
                        }

                        g.DrawString(title, fTitle, b, new RectangleF(marginWidth, (productImgHeight + productImgMarginTop + productImgMarginBottom), textRangeWidth, (titleHeight)));
                    }
                }

                int taobaoLogoTop = productImgMarginTop + productImgHeight + productImgMarginBottom + titleHeight + productTitleMarginBottom;
                //淘宝logo
                using (Image taobaoLogo = Image.FromFile(taobaoLogoImg))
                {
                    g.DrawImage(taobaoLogo, new Rectangle(30, taobaoLogoTop, taobaoLogo.Width, taobaoLogo.Height),
        0, 0, taobaoLogo.Width, taobaoLogo.Height, GraphicsUnit.Pixel);
                }

                int productOriginAmountTop = taobaoLogoTop + 7;
                //原价
                using (Font fTitle = new Font("宋体", 20f, FontStyle.Regular))
                {
                    using (Brush b = new SolidBrush(Color.FromArgb(107, 107, 107)))
                    {
                        g.DrawString($"现价 ¥ {originalPrice}", fTitle, b, new RectangleF((30 + 45), productOriginAmountTop, 300, (titleHeight)));
                    }
                }
                int juanTop = taobaoLogoTop + taobaoImgBottom + 42;  //42为淘宝logo高度

                //todo:劵宽度根据劵金额位数动态生成
                int juanWidth = 120;
                //劵背景色
                using (Brush b = new SolidBrush(Color.FromArgb(249, 68, 72)))
                {
                    g.FillRectangle(b, new Rectangle(30, juanTop, juanWidth, 40));
                }
                //劵logo上文案 劵 劵金额
                using (Font fTitle = new Font("黑体", 21f, FontStyle.Bold))
                {
                    using (Brush b = new SolidBrush(Color.FromArgb(255, 255, 255)))
                    {
                        g.DrawString("劵 50元", fTitle, b, new RectangleF(35, juanTop + 5, 200, 40));  //40:劵图片高度
                    }
                }
                //劵后价
                using (Font fFont = new Font("宋体", 22f, FontStyle.Regular))
                {
                    using (Brush b = new SolidBrush(Color.FromArgb(249, 71, 74)))
                    {
                        g.DrawString("劵后价", fFont, b, new RectangleF(30 + juanWidth + 15, juanTop + 5, 200, 40));  //40:劵图片高度
                    }
                }
                //劵后价 ¥
                using (Font fFont = new Font("黑体", 22f, FontStyle.Bold))
                {
                    using (Brush b = new SolidBrush(Color.FromArgb(249, 71, 74)))
                    {
                        g.DrawString("¥", fFont, b, new RectangleF(30 + juanWidth + 15 + 95, juanTop + 5, 200, 40));  //40:劵图片高度
                    }
                }
                //劵后价 金额
                using (Font fFont = new Font("黑体", 35f, FontStyle.Bold))
                {
                    using (Brush b = new SolidBrush(Color.FromArgb(249, 71, 74)))
                    {
                        g.DrawString($"{finalPrice}", fFont, b, new RectangleF(30 + juanWidth + 15 + 95 + 20, juanTop - 10, 200, 40));  //40:劵图片高度
                    }
                }
                //分割线
                {
                    using (Brush b = new SolidBrush(Color.FromArgb(230, 230, 230)))
                    {
                        Pen p = new Pen(b, 1);
                        g.DrawLine(p, 30, juanTop + 80, productImgHeight, juanTop + 80);  //绘制直线
                    }
                }

                using (Font fFont = new Font("黑体", 20f, FontStyle.Regular))
                {
                    using (Brush b = new SolidBrush(Color.FromArgb(150, 150, 150)))
                    {
                        g.DrawString("1.长按识别图中二维码", fFont, b, new RectangleF(30, juanTop + 80 + 80, 360, 40));  //40:劵图片高度
                        g.DrawString("2.打开后一键复制淘口令", fFont, b, new RectangleF(30, juanTop + 80 + 80 + 50, 360, 40));  //40:劵图片高度
                        g.DrawString("3.打开淘宝领劵购买", fFont, b, new RectangleF(30, juanTop + 80 + 80 + 50 + 50, 360, 40));  //40:劵图片高度
                    }
                }
                //二维码
                using (Image qrcodeImg = Image.FromFile(qrcodePath))
                {
                    g.DrawImage(qrcodeImg, new Rectangle(500, juanTop + 120, 200, 200),
        0, 0, qrcodeImg.Width, qrcodeImg.Height, GraphicsUnit.Pixel);
                }
            }

            var catalogConfig = AppSettingConfigExtensions.GetUploadFileConfigInfo("PosterImg");
            var catalog = $@"\{ DateTime.Now.ToString("yyyyMM")}\{ DateTime.Now.ToString("yyyyMMdd")}";
            var fileName = $@"{ Guid.NewGuid().ToString("N")}.png";
            if (!Directory.Exists($@"{catalogConfig.SavePath}\{catalog}"))
                Directory.CreateDirectory($@"{catalogConfig.SavePath}\{catalog}");
            var posterSavePath = $@"{catalogConfig.SavePath}\{catalog}\{fileName}";

            imgSrc.Save(posterSavePath);
            //图片压缩
            //ImageCompressHelper.Compress(imgSrc, newFilePath, 50);
            result.Code = 200;
            result.Data = new PosterCompoundModel()
            {
                PosterImgUrl = $@"{catalogConfig.SaveUrl}\{catalog}\{fileName}"
            };
            return result;
        }

        private static async Task<Image> UrlToImage(string url)
        {
            WebClient mywebclient = new WebClient();
            byte[] Bytes = await mywebclient.DownloadDataTaskAsync(url);
            using (MemoryStream ms = new MemoryStream(Bytes))
            {
                Image outputImg = Image.FromStream(ms);
                return outputImg;
            }
        }
    }
}
